package com.meixiang.activity.account.manager;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.login.LoginActivity;
import com.meixiang.activity.account.managers.BindBankCardActivity;
import com.meixiang.dialog.AlertDialogFragment;
import com.meixiang.dialog.SelectPhotoDialogFragment;
import com.meixiang.dialog.TitleSelectDialog;
import com.meixiang.entity.account.IndexInfos;
import com.meixiang.entity.account.UserInfo;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.main.MainActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbToastUtil;
import com.meixiang.util.GlideHelper;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 账户管理
 * author：xiejingwen
 */
public class AccountManageActivity extends BaseActivity implements OnRefreshListener, SelectPhotoDialogFragment.PhotoSelectListener {
    private Activity mActivity;
    private static final String TAG = "AccountManageActivity";
    @Bind(R.id.iv_head_portrait)
    ImageView ivHeadPortrait;
    @Bind(R.id.ll_head_portrait)
    LinearLayout llHeadPortrait;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.ll_name)
    RelativeLayout llName;
    @Bind(R.id.tv_sex)
    TextView tvSex;
    @Bind(R.id.ll_sex)
    RelativeLayout llSex;
    @Bind(R.id.tv_age)
    TextView tvAge;
    @Bind(R.id.ll_age)
    RelativeLayout llAge;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.ll_address)
    RelativeLayout llAddress;
    @Bind(R.id.tv_safety)
    TextView tvSafety;
    @Bind(R.id.ll_safety)
    LinearLayout llSafety;
    @Bind(R.id.tv_button)
    TextView tvLogin;

    @Bind(R.id.iv_bank_card_point)
    ImageView ivBankCardPoint;
    @Bind(R.id.ll_bank_card)
    LinearLayout llBankCard;
    @Bind(R.id.mrefresh)
    SwipeToLoadLayout mrefresh;
    @Bind(R.id.swipe_target)
    ScrollView swipeTarget;

    private List<File> files =new ArrayList<>();

    private IndexInfos indexInfo;
    private UserInfo mUserInfo;
    private String userName;

    private static final int PHOTO_GRAPH = 0x01;//拍照
    private static final int LOCAL_IMAGE = 0x02;//本地图片
    private static final int REQUEST_CODE_CAMERA = 0x03; // 拍照的权限
    private static final int CROP_IMAGE = 0x04; // 裁剪图片

    private Uri photoUri;

    private  String sexType;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_account_manage);
        ButterKnife.bind(this);
        mActivity=AccountManageActivity.this;
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        setTitle(getResources().getString(R.string.account_manage_title));
    }

    @Override
    protected void initView() {
        mrefresh.setOnRefreshListener(this);

    }

    @Override
    protected void setData() {
        status.showLoading();
        getIndex();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!MXApplication.mApp.hasLogin()){
            startActivity(MainActivity.class);
        }else{
            onRefresh();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        HttpUtils.tagCancelRequest(TAG);
    }

    @OnClick({R.id.ll_head_portrait, R.id.ll_name, R.id.ll_sex, R.id.ll_age, R.id.ll_address, R.id.ll_safety, R.id.tv_button, R.id.ll_bank_card})
    public void onClick(View view) {
        if (Tool.isFastDoubleClick()) return;
        switch (view.getId()) {
            case R.id.ll_head_portrait: //头像
                SelectPhotoDialogFragment.newInstance().setPhotoSelectListener(this).
                        show(getSupportFragmentManager(), SelectPhotoDialogFragment.TAG);

                break;
            case R.id.ll_name://昵称

                Intent intents=new Intent(mActivity,EditNickNameActivity.class);
                intents.putExtra("MemberName",indexInfo.getMemberName());
                startActivity(intents);

                break;
            case R.id.ll_sex://性别
                new TitleSelectDialog(this, "性别", "完成", tvSex.getText().toString(), new String[]{ "男", "女", "保密"}, new TitleSelectDialog.IResultListener() {

                    @Override
                    public void RightTitleOnclick(View view, int selectedIndex, String item) {
                        tvSex.setText(item);
                        if (item.equals("男")){//0保密 1男 2女
                            sexType="1";
                        }
                        if (item.equals("女")){//0保密 1男 2女
                            sexType="2";
                        }
                        if (item.equals("保密")){//0保密 1男 2女
                            sexType="0";
                        }
                        getChangeSex(sexType);
                    }

                });

                break;
            case R.id.ll_age://年龄
                String[] data = new String[70];
                for (int i = 0; i < data.length; i++) {
                    data[i] = 12 + i + "岁";
                }
                new TitleSelectDialog(this, "年龄", "完成", tvAge.getText().toString(), data, new TitleSelectDialog.IResultListener() {

                    @Override
                    public void RightTitleOnclick(View view, int selectedIndex, String item) {
                        tvAge.setText(item);
                        getChangeAge(item.substring(0,2));
                    }

                });
                break;
            case R.id.ll_address://地址
                startActivity(new Intent(this, AddressManageActivity.class));
                break;
            case R.id.ll_safety://安全
                startActivity(new Intent(this, AccountSafetyActivity.class));
                break;
            case R.id.tv_button://登录or退出
                new AlertDialogFragment.Builder()
                        .setContentText("确认后无法看到个人信息\n确认退出？")
                        .setLeftBtnText("取消")
                        .setRightBtnText("确认")
                        .setRightClickCallBack(new AlertDialogFragment.RightClickCallBack() {
                            @Override
                            public void dialogRightBtnClick() {
                                loginOut();

                                loginOutQQ();
                                loginOutWEIXIN();
                            }
                        })
                        .build()
                        .show(getSupportFragmentManager(), AlertDialogFragment.TAG);

                break;
            case R.id.ll_bank_card://银行卡
//                private String   realname;//真实姓名
//                private String  realnameStatus;//实名认证状态
//                if(realnameStatus.equals("0")){
//                     AbToastUtil.showToast(AccountManageActivity.this,"您还未实名认证");
//                    return;
//                }

                if(userName==null){
                    getUserinfo();
                }
                Intent intent = new Intent();
                intent.putExtra("realname", userName);
                intent.setClass(this, BindBankCardActivity.class);
                startActivity(intent);
                break;
        }
    }


    private void loginOut() {
        HttpUtils.post(Config.SERVER_URL + "logout", null, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                startActivity(new Intent(context, LoginActivity.class));
                MXApplication.mApp.logout();
                if(!TextUtils.isEmpty(MXApplication.mApp.getSession().get("fundSessionId"))){
                    fundLogout();
                }
                finish();
                AbToastUtil.showToast(context, message);
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(context, message);
            }
        });
    }


    //yangdecheng 20160920
    private void loginOutQQ(){
        Platform plat = ShareSDK.getPlatform(QZone.NAME);
        CookieSyncManager.createInstance(plat.getContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
        // ///////////////////////////////////////

        Platform.ShareParams sp = new Platform.ShareParams();
        if(plat.isValid()) {
            plat.removeAccount();
        }


       /* plat.removeAccount();
        ShareSDK.removeCookieOnAuthorize(true);// 清理cookie */

    }

    //yangdecheng 20160920
    private void loginOutWEIXIN(){
        Platform plat = ShareSDK.getPlatform(Wechat.NAME);
        CookieSyncManager.createInstance(plat.getContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
        // ///////////////////////////////////////
        Platform.ShareParams sp = new Platform.ShareParams();
        if(plat.isValid()) {
            plat.removeAccount();
        }

       /* plat.removeAccount();
        ShareSDK.removeCookieOnAuthorize(true);// 清理cookie */

    }


    /**
     * 退出基金业务（在用户退出美享app时调用）
     */
    public void fundLogout(){
        HttpUtils.getC(Config.FUND_LOGOUT, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Log.i("message","message = "+message);
                MXApplication.mApp.fundLogout();
            }

            @Override
            public void onError(String code, String message) {

            }
        });
    }


    private void getIndex() {
        HttpUtils.get(Config.INDEX_URL, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                    status.removeView();
                    indexInfo = new Gson().fromJson(result.toString(), IndexInfos.class);
                    tvName.setText(indexInfo.getMemberName());
                    tvAge.setText(indexInfo.getMemberAge() + "岁");
                    if (indexInfo.getMemberSex().equals("1")) {//
                        tvSex.setText("男");
                    } else if (indexInfo.getMemberSex().equals("2")) {
                        tvSex.setText("女");
                    } else {
                        tvSex.setText("保密");
                    }
                    if (indexInfo.getDefaultAddress().equals("")) {
                        tvAddress.setText("暂无");
                    } else {
                        tvAddress.setText(indexInfo.getDefaultAddress());
                    }
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(AccountManageActivity.this, message);
                status.showNoNewWork(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getIndex();
                    }
                });
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                if (mrefresh.isRefreshing()){
                    mrefresh.setRefreshing(false);
                }
            }
        });


    }

    private void getUserinfo() {

        HttpUtils.get(Config.USERINFO_URL, new HttpCallBack(AccountManageActivity.this, null) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                userName = result.optString("memberTruename")/*mUserInfo.getMemberTruename()*/;//memberTruename
                GlideHelper.showCircleImage(context, result.optString("memberAvatar") /*mUserInfo.getMemberAvatar()*/, R.mipmap.default_head_portrait, ivHeadPortrait);
                HashMap<String, String> vals = new HashMap<String, String>();
                vals.put("MemberMobile", result.optString("memberMobile"));
                MXApplication.mApp.getSession().set(vals);
            }
            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(AccountManageActivity.this, message);
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                if (mrefresh.isRefreshing()){
                    mrefresh.setRefreshing(false);
                }
            }
        });

    }

    private void getChangeSex(String sex) {
        HttpParams params = new HttpParams();
        params.put("memberSex",sex);//memberSex

        HttpUtils.post(Config.SAVENICKNAME_URL, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (code.equals("0")) {
                    AbToastUtil.showToast(mActivity, message);
                }
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(mActivity, message);
            }
        });
    }

    private void getChangeAge(String age) {
        HttpParams params = new HttpParams();
        params.put("memberAge",age);

        HttpUtils.post(Config.SAVENICKNAME_URL, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (code.equals("0")) {
                    AbToastUtil.showToast(mActivity, message);
                }
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(mActivity, message);
            }
        });

    }

    @Override
    public void onRefresh() {
        getUserinfo();
        getIndex();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == MainActivity.RESULT_OK) {
            if (requestCode == PHOTO_GRAPH) {//拍照
                Uri result;
                if (data != null) {
                    result = data.getData();
                } else {
                    result = photoUri;
                }
                photoUri = result;
                cropImageUri(photoUri);
            } else if (requestCode == LOCAL_IMAGE) {//本地图片
                if (data != null) {
                    Uri result = data.getData();
                    if (result != null) {
                        photoUri = result;

                        cropImageUri(photoUri);

                        Log.e("TAG","输出图片地址=="+photoUri);
                    }
                }
            } else if (requestCode == CROP_IMAGE) {
                if (photoUri != null) {
                    sendPicByUri(photoUri);
                } else {
                    Toast.makeText(activity, "照片获取失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 根据图库图片uri发送图片
     *
     * @param selectedImage
     */
    private void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = MXApplication.mApp.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        String str = "未能找到任何图片";
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            if (picturePath == null || picturePath.equals("null")) {
                Toast.makeText(activity, str, Toast.LENGTH_SHORT).show();
                return;
            }
            uploadImage(new File(picturePath));
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast.makeText(activity, str, Toast.LENGTH_SHORT).show();
                return;
            }
            uploadImage(file);
        }

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @PermissionGrant(REQUEST_CODE_CAMERA)
    public void requestSdcardSuccess() {
        Intent openFileIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        openFileIntent.putExtra(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        String filename = "temp";
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Media.TITLE, filename);
        photoUri = MXApplication.mApp.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        openFileIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(openFileIntent, PHOTO_GRAPH);
    }

    @PermissionDenied(REQUEST_CODE_CAMERA)
    public void requestSdcardFailed() {
        new AlertDialogFragment.Builder()
                .setContentText("为了能正常上传头像,请开启相机权限与储存权限")
                .setLeftBtnText("取消")
                .setRightBtnText("手动授权")
                .setRightClickCallBack(new AlertDialogFragment.RightClickCallBack() {
                    @Override
                    public void dialogRightBtnClick() {
                        Uri uri=Uri.parse("package:"+getPackageName());//包名，指定该应用"com.yingke.teyi"
                        Intent intent=new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", uri);
                        startActivity(intent);
                    }
                })
                .build()
                .show(getSupportFragmentManager(), AlertDialogFragment.TAG);
    }
    @Override
    public void takePhoto() {
        //拍照
        MPermissions.requestPermissions(AccountManageActivity.this, REQUEST_CODE_CAMERA, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA});
    }
    @Override
    public void selectPhotoAlbum() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, LOCAL_IMAGE);
    }

    /**
     * 上传头像
     */
    private void uploadImage(File file) {
        HttpParams params=new HttpParams();
        params.put("attachment",file);//        params.put("attachment",file);


        HttpUtils.postFile(Config.IMGEFILLEUPLOAD_URL, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                try {
                    String headerPic = result.getString("memberAvatar");
                    GlideHelper.showCircleImage(activity, headerPic, R.mipmap.default_head_portrait,ivHeadPortrait);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
            }
        });



    }

    /**
     * 进入裁剪页面
     *
     * @param uri
     */
    private void cropImageUri(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", "1");
        intent.putExtra("aspectY", "1");
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, CROP_IMAGE);

    }


}
